package com.example.lenovo.asia5b.commodity.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import com.example.lenovo.asia5b.commodity.adapter.SearchAdapter;
import com.example.lenovo.asia5b.commodity.adapter.SearchTwoAdapter;
import com.example.lenovo.asia5b.commodity.bean.ClassifyBean;
import com.example.lenovo.asia5b.commodity.bean.SearchBean;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import app.BaseActivity;
import fay.frame.ui.U;
import com.example.lenovo.asia5b.ui.DownloadPicture;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.ui.PullToRefreshLayout;
import com.example.lenovo.asia5b.ui.SelectPicPopupWindow;
import com.example.lenovo.asia5b.util.DensityUtil;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.Setting;

import static com.wushi.lenovo.asia5b.R.drawable.icon_ascending;
import static com.wushi.lenovo.asia5b.R.drawable.icon_descending;
import static com.wushi.lenovo.asia5b.R.id.public_btn_left;
import static com.wushi.lenovo.asia5b.R.id.txt_camera;

/**
 * 搜索界面
 * Created by lenovo on 2017/7/17.
 */

public class SearchActivity extends BaseActivity implements ICallBack, PullToRefreshLayout.OnRefreshListener{
    private GridView lv_search;
    private SearchAdapter adapter;
    private SearchTwoAdapter adapterTwo;
    private LoadingDalog loadingDalog;
    private int page  = 1;
    private int countPage = 0;
    private PullToRefreshLayout pullToRefreshLayout;
    private List<SearchBean> lists = null;
    //标题
    private  List<TextView> tits = new ArrayList<TextView>();
    //横线
    private  List<TextView> stripings = new ArrayList<TextView>();
    //排序字段
    private String sortfield = "price";
    // 当前选中
    public int currentIndex;
    //0：倒序，1：顺序；默认为1
    private String sorttype = "1";
    private String brand = "0",catagory= "0",min_price= "0",max_price = "0";
    private   List<ClassifyBean> listCats;
    private   List<ClassifyBean> listBrands;
    //3种列表状态0为初始，2为网格，3为图片大的
    private  int typtId = 1;
    //有值说明用户是根据照相来查找的
    public static String photoFile = "";
    //判断当前数据是从搜索获取或者是从照相获取
    public static  boolean isSearch = true;

    private boolean isCamera = true;
    private  boolean isOne = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        initView();
        if (!getIntent().hasExtra("photoFile")) {
            searchData();
        } else {
            photoSearchData();
        }
    }
    public void initView() {
        loadingDalog = new LoadingDalog(this);
        loadingDalog.show();
        F.id(R.id.btn_change_information).clicked(this);
        F.id(R.id.txt_screen).clicked(this);
        F.id(R.id.public_title_name).text(getResources().getString(R.string.ss));
        F.id(R.id.btn_classify).clicked(this);
        pullToRefreshLayout = ((PullToRefreshLayout)findViewById(R.id.refresh_view));
        pullToRefreshLayout.setOnRefreshListener(this);
        F.id(public_btn_left).clicked(this);
        F.id(txt_camera).clicked(this);
        lv_search = (GridView)findViewById(R.id.lv_search);
        adapter = new SearchAdapter(this);
        adapterTwo = new SearchTwoAdapter(this);
        lv_search.setAdapter(adapter);
        lv_search.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(SearchActivity.this,CommodityDetActivity.class);
                intent.putExtra("goods_id",adapter.getLists().get(i).goods_id);
                startActivity(intent);
            }
        });
        lv_search.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
            }
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // 当不滚动时
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (view.getLastVisiblePosition() == view.getCount() - 1) {
                        if (page < countPage) {
                            page += 1;
                            searchData();
                        } else {
                            TextView load_tv = (TextView)findViewById(R.id.load_tv);
                            load_tv.setText(getResources().getString(R.string.no_more_data));
                            load_tv.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        });
        F.id(R.id.edit_content).getEditText().setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId,KeyEvent event)  {
                if (actionId== EditorInfo.IME_ACTION_SEND ||(event!=null&&event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                {
                    String url = F.id(R.id.edit_content).getText().toString();
                    if (url.indexOf("复制这条信息") > -1 ||url.indexOf("复制整段信息") > -1) {
                        if (!isOne) {
                            Intent intent = new Intent(SearchActivity.this, CommodityDetActivity.class);
                            intent.putExtra("tmall", url);
                            startActivity(intent);
                            isOne = true;
                        } else {
                            isOne = false;
                        }
                    } else  {
                        loadingDalog.show();
                        page  = 1;
                        searchData();
                    }
                    return true;
                }
                return false;
            }
        });
        F.id(R.id.edit_content).getEditText().addTextChangedListener(new EditRemarkdListener());
        tits.add(F.id(R.id.txt_price).getTextView());
        tits.add(F.id(R.id.txt_popularity).getTextView());
        tits.add(F.id(R.id.txt_sales).getTextView());
        tits.add(F.id(R.id.txt_overal).getTextView());
        for (int i = 0; i< tits.size(); i++) {
            tits.get(i).setOnClickListener(this);
            //判断当前控件是否被选中
            tits.get(i).setTag(false);
        }
        //先默认第一个被选中
        tits.get(0).setTag(true);
        stripings.add(F.id(R.id.txt_one).getTextView());
        stripings.add(F.id(R.id.txt_two).getTextView());
        stripings.add(F.id(R.id.txt_three).getTextView());
        stripings.add(F.id(R.id.txt_four).getTextView());
    }

    /**
     * 获取搜索数据
     */
    public void searchData() {
        isSearch = true;
        //搜索关键字
        String content =F.id(R.id.edit_content).getText().toString();
        //排序字段
        String sortfield = this.sortfield;
        //排序类型
        String sorttype = this.sorttype;
        //品牌id
        String brand = this.brand;
        //分类id
        String catagory = this.catagory;
        //最小价格
        String min_price =this.min_price;
        //最大价格
        String max_price = this.max_price;

        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.SEARCH;
//            String url = "http://192.168.2.208"+ "/api/goods.php?act=search";
            parmaMap.put("content", content);
            parmaMap.put("sortfield", sortfield);
            parmaMap.put("sorttype", sorttype);
            parmaMap.put("page",""+page);
            parmaMap.put("brand", brand);
            parmaMap.put("catagory",catagory);
            parmaMap.put("min_price", min_price);
            parmaMap.put("max_price", max_price);
            JsonTools.getJsonAll(this, url, parmaMap, 0);
        }catch (Exception e) {

        }

    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case public_btn_left:
                finish();
                break;
            case R.id.txt_overal:
                sortfield = "overall";
                boolean isSelect = (Boolean) tits.get(3).getTag();
                if (isSelect) {
                    tits.get(3).setTag(false);
                    sorttype = "0";
                } else {
                    changBootUI(3);
                    sorttype = "1";
                }
                page =1;
                searchData();
                break;
            case  R.id.txt_popularity:
                sortfield = "popularity";
                boolean isSelect1 = (Boolean) tits.get(1).getTag();
                if (isSelect1) {
                    tits.get(1).setTag(false);
                    sorttype = "0";
                } else {
                    changBootUI(1);
                    sorttype = "1";
                }
                page =1;
                searchData();
                break;
            case R.id.txt_sales:
                sortfield = "sales";
                boolean isSelect2 = (Boolean) tits.get(2).getTag();
                if (isSelect2) {
                    tits.get(2).setTag(false);
                    sorttype = "0";
                } else {
                    changBootUI(2);
                    sorttype = "1";
                }
                page =1;
                searchData();
                break;
            case R.id.txt_price:
                sortfield = "price";
                boolean isSelect3 = (Boolean) tits.get(0).getTag();
                if (isSelect3) {
                    tits.get(0).setTag(false);
                    sorttype = "1";
                    Drawable drawable= getResources().getDrawable(icon_ascending);
                    /// 这一步必须要做,否则不会显示.
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    F.id(R.id.txt_price).getTextView().setCompoundDrawables(drawable,null,null,null);
                } else {
                    changBootUI(0);
                    sorttype = "0";
                    Drawable drawable= getResources().getDrawable(icon_descending);
                    /// 这一步必须要做,否则不会显示.
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    F.id(R.id.txt_price).getTextView().setCompoundDrawables(drawable,null,null,null);
                }
                page =1;
                searchData();
                break;
            case R.id.txt_screen:
                intent = new Intent(SearchActivity.this, SelectPicPopupWindow.class);
                intent.putExtra("cat",(Serializable)listCats);
                intent.putExtra("brand",(Serializable)listBrands);
                startActivityForResult(intent,0);
                break;
            case R.id.btn_classify:
                if (typtId ==0) {
                    typtId =1;
                    lv_search.setNumColumns(1);
                    lv_search.setVerticalSpacing(0);
                    lv_search.setAdapter(adapter);
                    F.id(R.id.btn_classify).background(R.drawable.main_home_tit_sort1);
                }
                else if(typtId == 1){
                    typtId = 2;
                    lv_search.setNumColumns(2);
                    lv_search.setVerticalSpacing(DensityUtil.dip2px(SearchActivity.this,10));
                    adapterTwo.setIsTwo(true);
                    lv_search.setAdapter(adapterTwo);
                    F.id(R.id.btn_classify).background(R.drawable.main_home_tit_sort2);
                }  else if(typtId == 2){
                    typtId = 0;
                    lv_search.setNumColumns(1);
                    lv_search.setVerticalSpacing(DensityUtil.dip2px(SearchActivity.this,10));
                    adapterTwo.setIsTwo(false);
                    lv_search.setAdapter(adapterTwo);
                    F.id(R.id.btn_classify).background(R.drawable.main_home_tit_sort3);
                }
                break;
            case R.id.txt_camera:
                if (isCamera) {
                    loadingDalog.showPhoto();
                } else {
                    F.id(R.id.edit_content).text("");
                }
                break;
            default:
                break;

        }
    }

    /**
     * 向下刷新
     */
    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        loadingDalog.show();
        page = 1;
        searchData();
    }


    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json =  (JSONObject)result;
                        int state = (int)json.getInt("State");
                        if (state == 0) {
                            JSONObject paging = json.getJSONObject("paging");
                            if (null!=paging.getString("page") && "1".equals(paging.getString("page"))){
                                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                                initPaging(paging);
                                JSONArray goods = json.getJSONArray("goods");
                                lists = Logic.getListToBean(goods,new SearchBean());
                                adapter.setLists(lists);
                                adapterTwo.setLists(lists);
                                adapter.notifyDataSetChanged();
                                adapterTwo.notifyDataSetChanged();
                                JSONArray sel = json.getJSONArray("sel");
                                JSONArray brandlist = sel.getJSONArray(0);
                                listBrands = Logic.getListToBean(brandlist, new ClassifyBean());
                                JSONArray catagorylist = sel.getJSONArray(1);
                                listCats = Logic.getListToBean(catagorylist, new ClassifyBean());

                            }  else if(null!=paging.getString("page") && !"1".equals(paging.getString("page"))){
                                pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                                JSONArray goods = (JSONArray) json.get("goods");
                                if (null != goods && goods.length() > 0) {
                                    List<SearchBean> listBean  =  Logic.getListToBean(goods,new SearchBean());
                                    for (int i = 0; i < listBean.size(); i++) {
                                        lists .add(listBean.get(i));
                                    }
                                    adapter.setLists(lists);
                                    adapterTwo.setLists(lists);
                                    adapter .notifyDataSetChanged();
                                    adapterTwo.notifyDataSetChanged();
                                } else {
                                    page = page - 1;
                                }

                            }
                        }  else if(state == 1){
                            U.Toast(SearchActivity.this,getResources().getString(R.string.qmsb));
                        }else if(state == 2){
                            U.Toast(SearchActivity.this,getResources().getString(R.string.cscw));
                        }
                    } catch (Exception e) {
                    }
                }
                loadingDalog.dismiss();
                pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
            }
            if (action == 1) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json =  (JSONObject)result;
                        int state = (int)json.getInt("State");
                        if (state == 0) {
                        }  else if(state == 1){
                            U.Toast(SearchActivity.this,getResources().getString(R.string.qmsb));
                        }else if(state == 2){
                            U.Toast(SearchActivity.this,getResources().getString(R.string.cscw));
                        }else if(state == 3){
                            U.Toast(SearchActivity.this,getResources().getString(R.string.wdl));
                        }else if(state == 4){
                            U.Toast(SearchActivity.this,getResources().getString(R.string.mysj));
                        }
                    } catch (Exception e) {
                    }
                }
            }
        }
    };


    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }


    /**
     * 向上加载
     */
    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
    }

    public void initPaging(JSONObject json) throws JSONException {
        String pageSizeString = json.getString("count");
        String countPageString = json.getString("countpage");
        String pageString = json.getString("page");
        if (pageSizeString != null && countPageString != null && pageString != null) {
            countPage = Integer.parseInt(countPageString);
            if (countPage <= 1) {
                pullToRefreshLayout.stopLoadMore();
            }
        }
    }
    // 重置按钮,
    public void  changBootUI(int selectId){
        for (int i = 0; i < tits.size();i++) {
            tits.get(i).setTextColor(ContextCompat.getColor(SearchActivity.this,R.color.my_333));
            stripings.get(i).setVisibility(View.INVISIBLE);
            tits.get(i).setTag(false);
        }
        tits.get(selectId).setTextColor(ContextCompat.getColor(SearchActivity.this,R.color.wathet2));
        stripings.get(selectId).setVisibility(View.VISIBLE);
        tits.get(selectId).setTag(true);
    }

    // 回调方法，从第二个页面回来的时候会执行这个方法
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case 0:
                if (data == null) {
                    return;
                }
                loadingDalog.show();
                brand = data.getStringExtra("brandsId");
                catagory = data.getStringExtra("catsId");
                min_price = data.getStringExtra("min_price");
                if (TextUtils.isEmpty(min_price)) {
                    min_price = "0";
                }
                max_price = data.getStringExtra("max_price");
                if (TextUtils.isEmpty(max_price)) {
                    max_price = "0";
                }
                page =1;
                searchData();
                break;
            case 101:// 相机
                if (data != null) {
                    if (data.getExtras() != null) {
                        Bundle bundle = data.getExtras();
                        Bitmap bitmap = bundle.getParcelable("data");
                        picture(bitmap);
                    } else {
                        U.Toast(SearchActivity.this,getResources().getString(R.string.system_no_getpic));
                    }
                } else {
                    if (loadingDalog.getPhotoUrihotoUri() != null) {
                        try {
                            Bitmap bitmap = MediaStore.Images.Media.getBitmap(SearchActivity.this.getContentResolver(), loadingDalog.getPhotoUrihotoUri());
                            if (null != bitmap) {
                                picture(DownloadPicture.smallOneFifth(bitmap));
                            } else {
                                U.Toast(SearchActivity.this,getResources().getString(R.string.system_no_getpic));
                            }
                        }catch (Exception e) {
                        }
                    } else {
                        U.Toast(SearchActivity.this,getResources().getString(R.string.system_no_getpic));
                    }
                }
                break;
            case 102:// 相册
                Uri uri = null;
                if (data != null) {
                    if (data.getData() != null) {
                        uri = data.getData();
                        try {
                            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                            if (null != bitmap) {
                                picture(DownloadPicture.smallOneFifth(bitmap));
                            }
                        }catch (Exception e) {
                        }
                    } else {
                        U.Toast(this,getResources().getString(R.string.system_no_getpic));
                    }
                } else {
                    U.Toast(this,getResources().getString(R.string.system_no_getpic));
                }
                break;
            default:
                break;
        }
    }

    //==========================================照图搜索======================================================

    /**
     * 照相后获取搜索结果
     */
    public void  photoSearchData() {
        isSearch = false;
        page  = 1;
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.PAI_SEARCH;

            parmaMap.put("photo", photoFile);
            JsonTools.getJsonAll(this, url, parmaMap, 0);
        }catch (Exception e) {

        }
    }


    public void picture(Bitmap photo) {
        BufferedOutputStream bos = null;
        if (photo != null) {
            File dirFile = new File(Setting.IMAGE_ROOTPATH);
            if (!dirFile.exists())
                dirFile.mkdirs();
            SimpleDateFormat sDateFormat = new SimpleDateFormat(
                    "yyyyMMddhhmmss", Locale.ENGLISH);
            File uploadFile = new File(dirFile + "/"
                    + sDateFormat.format(new java.util.Date())
                    + ".jpg");

            char[] chars = "0123456789abcdef".toCharArray();
            StringBuilder sb = new StringBuilder("");
            int bit;
            try {
                uploadFile.createNewFile();
                bos = new BufferedOutputStream(new FileOutputStream(uploadFile));
                photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                FileInputStream fis = new FileInputStream(uploadFile);
                byte[] b = new byte[fis.available()];
                fis.read(b);
                for (int i = 0; i < b.length; i++) {
                    bit = (b[i] & 0x0f0) >> 4;
                    sb.append(chars[bit]);
                    bit = b[i] & 0x0f;
                    sb.append(chars[bit]);
                }

                fis.close();
                photoFile = sb.toString();
                photoSearchData();
            } catch (IOException e) {
                U.Toast(SearchActivity.this, e.getLocalizedMessage());
            } finally {
                if (bos != null) {
                    try {
                        bos.flush();
                        bos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    class EditRemarkdListener implements TextWatcher {

        private CharSequence temp;//监听前的文本
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (TextUtils.isEmpty(s)) {
                F.id(R.id.txt_camera).background(R.drawable.icon_camera);
                isCamera = true;
            } else {
                F.id(R.id.txt_camera).background(R.drawable.icon_tf_clear);
                isCamera = false;
            }
        }
    };
}
